const mockHost =  'http://a.b.c'

async function handlerFetch(url: string, config: any = {}) {
    let response: any;
    try {
        const ret =  await fetch(url, {
            headers: {
                "Access-Control-Allow-Origin": "*",
                'X-Requested-With': 'XMLHttpRequest'
            },
            credentials: 'include',
            redirect: 'follow', 
            ...config
        });
        response = await ret.json();
    } catch (error) {
        console.log(error);
    }
    const {
        ok,
        success,
        status,
        data,
        errMsg,
        msg,
        message: msge,
    } = response;
    if (status === 302) {
        window.location.href = `/portal-web-system/usermanage/system?url=${window.location.href
          .replace(/\//g, '@')
          .replace(/#/g, '*')}`;
        return null;
      }
      if (ok || success) {
        return ['', null, undefined].includes(data) ? true : data; // 兼容 data 为 null 或者 undefined的行为
      }
    if (errMsg || msg || msge) {
        console.log(((errMsg || msg || msge).split(/\n/) || [])[0] || '')
        return data;
      }
        console.log('网络异常，请联系管理员！')
      return null;
}

export function fetchGet(url: string, params: any = {}) {
    const uri = new URL(mockHost+url);
    Object.keys(params).forEach(key => uri.searchParams.append(key, params[key]));
    const config = {
        method: 'GET',
    };
    return handlerFetch(uri.toString().replace(mockHost, ''), config);
}

export function fetchPost(url: string, data = {}, params: any = {}) {
    const uri = new URL(mockHost+url);
    Object.keys(params).forEach(key => uri.searchParams.append(key, params[key]));
    const config = {
        method: 'POST',
        body: JSON.stringify(data),
    };
    return handlerFetch(uri.toString().replace(mockHost, ''), config);
}